package ibatis;

import gui.common.msg.MsgType;
import gui.common.msg.SysMessage;

import java.sql.SQLException;
import java.util.List;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapException;


import data.User;
import data.dao.UserDao;

public class SqlMapUserDao implements UserDao{

	private SqlMapClient sd=SqlConfig.getSqlMapInstance();

	//Tested
	public User getUser(String username, String password) throws SQLException {
		User log=new User();
		log.setUsername(username);
		log.setPassword(password);
		return (User)sd.queryForObject("getUserByUsernameAndPassword",log);
	}

	//Tested
	public User getUserInfo(int userId) throws SQLException {
		return (User)sd.queryForObject("getUserById",userId);
	}

	//Tested
	public List<User> getUserList() throws SQLException {
		return (List<User>)sd.queryForList("getAllUser");
	}

	//Tested
	public User addUser(String username, String password) throws SQLException {
		int userid=SeedProvider.getSeed(User.seedName);
		User user=new User();
		user.setId(userid);
		user.setPassword(password);
		user.setUsername(username);
		sd.insert("insertUser",user);
		return user;
	}


	public SysMessage deleteUser(User user) throws SQLException {
		SysMessage msg=new SysMessage();
		sd.delete("deleteUser", user);
		if(sd.queryForObject("getUserById",user.getId())!=null){
			msg.type=MsgType.Error;
			msg.subject="delete user failed";
		}else{
			msg.type=MsgType.Success;
			msg.subject="delete user success";
		}
		return msg;
	}

	public SysMessage updateUser(User user) throws SQLException {
		SysMessage msg=new SysMessage();
		msg.subject="Update User";
		User oldUser=(User)sd.queryForObject("getUserById",user.getId());
		System.out.println("State:"+oldUser.getState()+"State"+user.getState());
		if(oldUser!=null){

			if(oldUser.getPassword().equals(user.getPassword())&&oldUser.getState()==user.getState()){
				msg.type=MsgType.Warning;
				msg.detail="Need not update";
			}else {
				sd.update("updateUser", user);
				msg.type=MsgType.Success;
				msg.detail="Update User success";
			}

		}else{
			msg.type=MsgType.Error;
			msg.detail="No such user:"+user.getId();
		}

		return msg;
	}

}
